import React, { memo, useImperativeHandle, useRef, useState } from 'react';
import { intl, removeLocalStorageItem } from '@/utils';
import ProDialog from '@/pages/components/ProjectPopup';
import notify from 'devextreme/ui/notify';
import Zcbfpopup from './Zcbfpopup';
import { projectImport, getImportState, projectExist, isCheckProjectIsOpened } from '@/services/cpasRequest';
import { Progress } from 'antd';
import TipsPopup from '../../TipsPopup';


const ZcbfpopupMemo = memo(Zcbfpopup);

const SelZcbfPopup = React.forwardRef((props: any, ref: any) => {
  const [oneVisible, setOneVisible] = useState<boolean>(false);

  const refZcbfpopup = useRef<any>();

  const [isShowProgress, setIsShowProgress] = useState<boolean>(false);
  const [progressNumber, setProgressNumber] = useState<any>(0);
  const [projectinfo, setProjectinfo] = useState<string>('项目导入')
  const tipsPopup = useRef<any>();


  const identifyEvents_input = async (idss: []) => {
    try {
      const { rowsData } = refZcbfpopup.current.getSelectedRowsZcbfData();
      if (rowsData.length !== 0) {
        const ids = idss || rowsData.map(a => a.zcbfID)
        setIsShowProgress(true);
        setProgressNumber(0);
        const changeProcess = setInterval(async () => {
          const resState: any = await getImportState();
          setProgressNumber(resState.compressProcess);
        }, 1500);
        if (refZcbfpopup.current.getfileAddress() === '') {
          notify({ message: `请选择文件`, position: 'top center' }, "success", 1000);
        }
        let res = await projectImport({ filePath: refZcbfpopup.current.getfileAddress(), zcbfIds: ids })
        if (res.ok) {
          notify({ message: `导入项目成功！`, position: 'top center' }, "success", 1000);
          PubSub.publish('projectTreeRefresh', { msg: 'projectRefresh', xmbh: projectinfo });
          PubSub.publish('zcbfidsTreeRefresh', { msg: 'zcbfidsRefresh' });
          clearInterval(changeProcess);
          setProgressNumber(100);
          // 清空本地缓存
          ids.forEach((id) => {
            removeLocalStorageItem(id);
          });
          setOneVisible(false);
        } else {
          // setIsShowProgress(false);
          setProgressNumber(0);
          notify({ message: `导入项目失败：${res.data}`, position: 'top center' }, "error", 3000);
          clearInterval(changeProcess);
        }
        setTimeout(() => {
          setIsShowProgress(false);
        }, 500);
      }
    } catch (error) {
      notify({ message: `导入项目失败：${error}`, position: 'top center' }, "error", 3000);
      setIsShowProgress(false);
      setProgressNumber(0);
    }


  }

  useImperativeHandle(ref, () => ({
    showSelZcbfPopup: () => {
      setOneVisible(true);
      setProjectinfo('项目导入') // 清空上一次的渲染项目信息
      // 清空进度条
      setProgressNumber(0)
      //清空子组件
      refZcbfpopup.current.resetTreeList();

    },
  }));

  //PubSub.unsubscribe('ProjectPopupInfo');
  PubSub.subscribe('importProjectPopupInfo', (msg: any, data: any) => {
    if (data.msg === 'importProjectPopupInfoData') {
      // console.log(data,111)
      setProjectinfo(`项目导入-【${data.data[0].sjxmbh}】-${data.data[0].sjxmmc}`)
      //setModalTableTreeData(data.data);
    }
  });


  const SpinLoading = () => {
    return (
      <div className="headSpinLoading">
        <Progress percent={progressNumber} size="small" status="active" style={{ width: '40%' }} />
      </div>
    );
  };

  return (
    <>
      {isShowProgress && SpinLoading()}
      <TipsPopup ref={tipsPopup} determineBtn={identifyEvents_input} />
      <ProDialog
        title={intl('pro.PopupModal.SelectComponent', `${projectinfo}`)}
        visible={oneVisible}
        width={1030}
        height={600}
        {...props}
        hideOnOutsideClick={true}
        onHiding={() => {
          setOneVisible(false);
        }}
        onShown={() => {
          if (oneVisible) {
            //refProject.current.getDataGrid();
            // 获取子组建的的数据
          }
        }}
        onOK={async () => {
          try {
            // 点击确定检测项目是否存在，不存在直接导入，存在执行弹窗逻辑，弹窗的确定按钮，执行导入
            const { rowsData } = refZcbfpopup.current.getSelectedRowsZcbfData(); // 获取点击组成部分
            if (rowsData.length !== 0) {
              const ids = rowsData.map(a => a.zcbfID)
              try {
                // 判断组成部分是否打开，已经打开，无法导入要先关闭
                const resProject = await isCheckProjectIsOpened({ zcbfid: ids })
                // console.log(resProject)
                if (!resProject.ok) {
                  return false
                }

                if (resProject.data) {

                  notify({ message: `被审单位已经打开不能导入，请关闭打开的被审单位后再执行导入！`, position: 'top center' }, "warning", 2000);
                  return false;
                }

                // 判断项目是否存在
                const res = await projectExist({ filePath: refZcbfpopup.current.getfileAddress(), zcbfIds: ids })
                if (res.ok && res.data.length !== 0) {
                  tipsPopup.current.show(res.data)
                  // 执行弹窗
                } else {
                  // 执行直接导入
                  identifyEvents_input(ids)
                }
              } catch (e) {
                //console.log(e)
                notify({ message: "导入失败", position: 'top center' }, "warning", 3000)
                setIsShowProgress(false);
                setProgressNumber(0);
              }


            } else {
              notify({ message: "请选择组成部分！", position: 'top center' }, "warning", 3000)
            }
          } catch (error) {
            console.log(error)
            notify({ message: "请选择文件", position: 'top center' }, "warning", 3000)
          }
          return;
        }}
        onCancel={() => {
          setOneVisible(false);
        }}

      >
        <ZcbfpopupMemo ref={refZcbfpopup} />
      </ProDialog>
    </>
  );
});

export default SelZcbfPopup;